package cn.nuc.edu.onlinestore.controller;

import java.io.File;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.nuc.edu.onlinestore.entity.Goods;
import cn.nuc.edu.onlinestore.service.interfaces.IGoodsService;
import cn.nuc.edu.onlinestore.util.PageControl;
import cn.nuc.edu.onlinestore.util.Pager;

/**
 * 商品handler
 * @author 王凯
 *
 */
@Controller
@RequestMapping("/goods")
public class GoodsHandler {
	
	/**
	 * 商品业务逻辑
	 */
	@Autowired
	private IGoodsService goodsService;
	
	/**
	 * 跳转到添加用户的页面（受WEB-INF保护）
	 * @return
	 */
	@RequestMapping("/initadd")
	public String initadd() {
		return "forward:/WEB-INF/views/goods/add.jsp";
	}
	
	/**
	 * 新增商品
	 * @throws Exception 
	 */
	@RequestMapping("/add")
	public ModelAndView add(
			@RequestParam("gname") String gname,
			@RequestParam("gprice") Float gprice,
			@RequestParam("gimg") MultipartFile file,
			@RequestParam("gdesc") String gdesc,
			HttpServletRequest request,
			ModelAndView modelAndView) throws Exception {
		
		ServletContext context = request.getServletContext();
		Goods goods = new Goods();
		goods.setGname(gname);
		goods.setGprice(gprice);
		goods.setGdesc(gdesc);
		
		//将gimg接收到
		if(file.isEmpty()) {
			System.out.println("文件未上传！");
		} 
		else{
			//得到"/goods"的绝对路径
			String Path = context.getRealPath("/goods");
			
			//FileUtils是commons-io组件中的工具类
			FileUtils.copyInputStreamToFile(file.getInputStream(), 
					new File(Path, file.getOriginalFilename()));
		}
		
		//将img的路径设置到goods对象中相应的字段
		String imgpath = "goods/" + file.getOriginalFilename();
		goods.setGimg(imgpath);
		
		//执行添加商品的操作
		Integer rtn = goodsService.addGoods(goods);
		if(rtn > 0){
			modelAndView.setViewName("redirect:/goods/goods");
		}else{
			modelAndView.addObject("msg", "保存角色失败");
			modelAndView.setViewName("forward:/WEB-INF/views/goods/add.jsp");
		}
		return modelAndView;
	}
	
	/**
	 * 初始化修改页面
	 * 
	 */
	@RequestMapping(value = "/toedit/{id}", method = RequestMethod.GET)
	public ModelAndView toedit(
				@PathVariable("id") Integer id, 
				ModelAndView modelAndView) {

		//查询到商品的具体信息
		Goods goods = new Goods();
		goods.setGid(id);
		goods = goodsService.detail(goods);
		
		//保存到request范围内，带到页面上
		if (goods != null) {
			modelAndView.addObject("item", goods);
			modelAndView.setViewName("forward:/WEB-INF/views/goods/edit.jsp");
		} else {
			modelAndView.addObject("msg", "需要修改的角色不存在。");
			modelAndView.setViewName("forward:/goods/goods");
		}
		return modelAndView;
	}
	
	/**
	 * 修改角色信息
	 * @throws Exception 
	 * 
	 */
	@RequestMapping(value = "/edit")
	public ModelAndView edit(
			@RequestParam("gid") Integer gid,
			@RequestParam("gname") String gname,
			@RequestParam("gprice") Float gprice,
			@RequestParam(value = "gimg", required = false) MultipartFile file,
			@RequestParam("gdesc") String gdesc,
			@RequestParam("goodsstate") Integer goodsstate,
			HttpServletRequest request,
			ModelAndView modelAndView) throws Exception {

		//查询到商品的详细信息
		Goods goods = new Goods(); 
		goods.setGid(gid);
		goods = goodsService.detail(goods);
		
		//修改信息
		goods.setGname(gname);
		goods.setGprice(gprice);
		goods.setGdesc(gdesc);
		goods.setGoodsstate(goodsstate);
		
		//如果用户更新了图片将gimg接收到
		if(file != null && !file.isEmpty()) {
			String Path = request.getSession().getServletContext()
					                .getRealPath("/goods");
			//FileUtils是commons-io组件中的工具类
			FileUtils.copyInputStreamToFile(file.getInputStream(), 
					new File(Path, file.getOriginalFilename()));
			//将img的路径设置到goods对象中相应的字段
			String imgpath = "goods/" + file.getOriginalFilename();
			goods.setGimg(imgpath);
		}

		//执行修改操作
		Integer rtn = goodsService.edit(goods);
		if (rtn > 0) {
			modelAndView.setViewName("redirect:/goods/goods");
		} else {
			modelAndView.addObject("msg", "保存系统功能失败！");
			modelAndView.setViewName("forward:/WEB-INF/views/goods/edit.jsp");
		}
		return modelAndView;
	}

	/**
	 * 获取商品列表(后台)
	 */
	@RequestMapping("/goods{index}")
	public ModelAndView list(String keyword,
			@PathVariable(value = "index", required = false) Integer index,
			ModelAndView modelAndView) {
		
		//设置关键字
		String key = null;
		if (keyword != null) {
			key = "%" + keyword + "%";
		}
		
		//设置分页所需参数
		PageControl pc = new PageControl();
		Integer currindex = 1;
		if(index != null){
			currindex = index;
		}
		pc.setCurrentindex(currindex);
		pc.setPagesize(5);
		
		//后台不过滤下架商品
		Pager<Goods> pager = goodsService.list(key, pc, false);
		modelAndView.addObject("pager", pager);
		
		//设置跳转位置
		modelAndView.setViewName("forward:/WEB-INF/views/goods/list.jsp");
		
		return modelAndView;
	}
	
	/**
	 * 商品上架
	 */
	@RequestMapping("/hitshelves")
	public ModelAndView hitshelves(
			@RequestParam("gid") Integer gid,
			@RequestParam("hitcount") Integer hitcount,
			ModelAndView modelAndView) {
		
		//根据商品id获得商品的最新库存
		Goods goods = new Goods();
		goods.setGid(gid);
		goods = goodsService.detail(goods);
		
		//增加库存
		goods.setGcount(goods.getGcount() + hitcount);
		
		//执行上架操作
		goodsService.hitShelves(goods);
		
		//跳转到对应页面
		modelAndView.setViewName("forward:/goods/goods");
		
		return modelAndView;
	}
	
	/**
	 * 商品上架
	 */
	@RequestMapping("/inithitshelves{id}")
	public ModelAndView inithitshelves(
			@PathVariable("id") Integer id,
			ModelAndView modelAndView) {
		
		//得到具体的商品信息
		Goods goods = new Goods();
		goods.setGid(id);
		goods = goodsService.detail(goods);
		
		//放入request
		modelAndView.addObject("item", goods);
		
		//跳转到对应页面
		modelAndView.setViewName("forward:/WEB-INF/views/goods/hitshelves.jsp");
		
		return modelAndView;
	}
	
	/**
	 * 商品上架
	 */
	@RequestMapping("/inithitlist")
	public ModelAndView inithitlist(ModelAndView modelAndView) {
		
		//得到上架列表
		List<Goods> list = goodsService.gethitlist();
		
		//放入request
		modelAndView.addObject("list",list);
		
		//跳转到对应页面
		modelAndView.setViewName("forward:/WEB-INF/views/goods/hitlist.jsp");
		
		return modelAndView;
	}
}
